package com.example.heathy_me.homeDetail;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.heathy_me.MyApplication;
import com.example.heathy_me.R;
import com.example.heathy_me.reportDetail.utils.reportDatabaseHelper;
import com.example.heathy_me.utils.RequestHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Report extends AppCompatActivity {
    public static final int TAKE_PHOTO=1;
    private static final int PERMISSIONS_REQUEST_CODE = 1;
    private static final int CAMERA_REQUEST_CODE = 2;
    private ImageView picture;
    private Uri imageUri;
    private String imageUrl;
    private TextView textView;
    private String reportreport;
    File mTmpFile;
    MyApplication app;

    private reportDatabaseHelper dbHelper;
    private String[] dbtitle={"title","content"};
    private String[] dbcontent;
    SimpleDateFormat formatter   =   new   SimpleDateFormat   ("HH:mm:ss");
    Date curDate =  new Date(System.currentTimeMillis());
    //获取当前时间
    String  title   =   formatter.format(curDate);


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (MyApplication) getApplication();
        setContentView(R.layout.activity_report);
        final Button takePhoto=(Button)findViewById(R.id.take_photo);
        Button savereport=(Button)findViewById(R.id.save_report);
        textView=(TextView)findViewById(R.id.ocrresult);
        picture=(ImageView)findViewById(R.id.picture);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    takePhoto();
            }
        });

        savereport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper=new reportDatabaseHelper(Report.this,"Report.db",null,1);
                SQLiteDatabase db=dbHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("title",title);
                values.put("content",textView.getText().toString());
                db.insert("report",null,values);
            }
        });

    }



    private void uploadMultiFile() {
        String imageType = "multipart/form-data";

        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), mTmpFile);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "file.jpg", fileBody)
                .addFormDataPart("imagetype", imageType)
                .build();

        Request request = new Request.Builder()
                .url(app.getUrl()+"ocr/")
                .post(requestBody)
                .build();

        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = httpBuilder
                .build();


        try (Response response = okHttpClient.newCall(request).execute()) {
            String htmlStr = response.body().string();
            Log.i("result", htmlStr);
            String result;
            RequestHelper r = new RequestHelper();

            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(htmlStr);
                result = jsonObject.getString("result");
                textView.setText(result);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                String htmlStr = response.body().string();
//                Log.i("result", htmlStr);
//
//                String result;
//                RequestHelper r = new RequestHelper();
//
//                JSONObject jsonObject;
//                try {
//                    jsonObject = new JSONObject(htmlStr);
//                    result = jsonObject.getString("result");
//                    textView.setText(result);
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//                //reportreport=htmlStr;
//
//            }
//
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
//            }
//
//
//
//        });

    }


    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private String getOCRresult(String reportreport){
        String result="";
        RequestHelper r = new RequestHelper();

        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(reportreport);
            result = jsonObject.getString("result");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }



    private void takePhoto(){

        if (!hasPermission()) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/img";
        if (new File(path).exists()) {
            try {
                new File(path).createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String filename = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        mTmpFile = new File(path, filename + ".jpg");
        mTmpFile.getParentFile().mkdirs();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String authority = "com.example.Heathy_Me.fileProvider";
            imageUri = FileProvider.getUriForFile(this, authority, mTmpFile);
        } else {
            imageUri = Uri.fromFile(mTmpFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(intent, CAMERA_REQUEST_CODE);

    }

    private boolean hasPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CODE);
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (grantResults.length > 0) {
                for (int grantResult : grantResults) {
                    if (grantResult == PackageManager.PERMISSION_DENIED) {
                        return;
                    }
                }
                takePhoto();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            BitmapFactory.Options options2 = new BitmapFactory.Options();
            options2.inPreferredConfig = Bitmap.Config.RGB_565;
            options2.inSampleSize=2;
            Bitmap photo = BitmapFactory.decodeFile(mTmpFile.getAbsolutePath(),options2);
            picture.setImageBitmap(photo);
            //imageUrl=bitmapToBase64(photo);
            uploadMultiFile();
            Log.d("MainActivity", "");
            //textView.setText(getOCRresult(reportreport));
        }
    }
}
